//
//  ConnactViewController.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/19.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import MJRefresh

class ConnactViewController: BaseUIViewController {

    let tableView = UITableView.init(frame: .zero, style: .plain)
    
    var page = 1
    let dataArray = BehaviorRelay<[ConnactModel]>.init(value: [])
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "江苏新源".localized
        
        let addButton = UIButton().config
            .image(AppIcon.image("", size: 17, color: .white))
            .title("新增".localized)
            .font(.systemFont(ofSize: 14, weight: .medium))
            .addTarget(self, action: #selector(addNew))
            .view
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: addButton)
        
        tableView.config
            .backgroundColor(#colorLiteral(red: 0.9724436402, green: 0.972609818, blue: 0.9724331498, alpha: 1))
            .keyboardDismissMode(.interactive)
            .separatorStyle(.none)
            .rowHeight(UITableView.automaticDimension)
            .register(ConnactCell.self)
            .addTo(view)
            .makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
        
        let nodataView = NoDataView()
        tableView.addSubview(nodataView)
        
        dataArray.asObservable()
            .map{ $0.count > 0 }
            .bind(to: nodataView.rx.isHidden)
            .disposed(by: rx.disposeBag)
        
        dataArray.asObservable()
            .bind(to: tableView.rx.items(cellType: ConnactCell.self)) { [weak self] (_, model, cell) in
                cell.bind(model)
                cell.clickDetailClosure = {
                    let vc = ConnactDetailViewController(model: model)
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
                cell.clickDelete = {
                    self?.deleteConnact(model.id)
                }
                cell.clickEdit = {
                    let vc = AddConnact1ViewController.init(editModel: model)
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
            }.disposed(by: rx.disposeBag)
        
        let header = MJRefreshNormalHeader.init { [weak self] in
            self?.loadData()
        }
        header.lastUpdatedTimeLabel?.isHidden = true
        tableView.mj_header = header
        
        tableView.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: { [weak self] in
            self?.loadMoreData()
        })
        NotificationCenter.default.rx.notification(.reloadConnact)
            .subscribe(onNext: { [weak self] (_) in
                self?.loadData()
            }).disposed(by: rx.disposeBag)
        
        loadData()
    }
    
    func loadData() {
        ApiManager.concatList(1).loadCache()
            .dataModelMap(ConnactListModel.self)
            .map{ $0.list }
            .catchErrorJustReturn([])
            .subscribe(onNext: { [weak self] (data) in
                self?.tableView.mj_footer?.resetNoMoreData()
                self?.page = 2
                self?.dataArray.accept(data)
                self?.tableView.mj_header?.endRefreshing()
            }).disposed(by: rx.disposeBag)
    }
    
    func loadMoreData() {
        ApiManager.concatList(page).request()
            .dataModelMap(ConnactListModel.self)
            .map{ $0.list }
            .catchErrorJustReturn([])
            .subscribe(onNext: { [weak self] (data) in
                guard let self = self else { return }
                self.page += 1
                if data.count == 0 {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    return
                }
                let orginCount = self.dataArray.value.count
                self.dataArray.accept(self.dataArray.value + data)
                self.tableView.mj_footer?.endRefreshing()
                if orginCount > 0 {
                    self.tableView.scrollToRow(at: IndexPath.init(row: orginCount - 1, section: 0), at: .bottom, animated: false)
                }
            }).disposed(by: rx.disposeBag)
    }
    
    func deleteConnact(_ id: String) {
        let alert = UIAlertController.init(title: "系统提示".localized, message: "确定要删除这一条售后服务信息吗".localized, preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "取消".localized, style: .cancel, handler: nil))
        alert.addAction(UIAlertAction.init(title: "删除".localized, style: .destructive, handler: { [weak self] (_) in
            guard let self = self else { return }
            ApiManager.deleteConcat(id)
                .request()
                .filterCode200()
                .trackingLoading()
                .subscribe(onNext: { [weak self] (_) in
                    self?.loadData()
                }).disposed(by: self.rx.disposeBag)
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    @objc func addNew() {
        self.navigationController?.pushViewController(AddConnact1ViewController(), animated: true)
    }
    
    override func navigationBarStyle() -> NavigationBarStyle {
        return .baseColor
    }
}
